package com.jec.module.sysconfig.service.convertor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jec.module.sysconfig.dao.NumberEntryRepository;
import com.jec.module.sysconfig.entity.NumberEntry;
import com.jec.module.sysmonitor.dao.CardViewRepository;
import com.jec.module.sysmonitor.dao.NetUnitRepository;
import com.jec.module.sysmonitor.entity.view.CardView;
import com.jec.protocol.pdu.PduConstants;
import com.jec.utils.Response;

/**
 * Created by jeremyliu on 05/10/2016.
 */
@Service
public class NumberEntryConvertor implements Convertor<NumberEntry> {

    @Autowired
    private NetUnitRepository netUnitRepository;

    @Autowired
    private NumberEntryRepository numberEntryRepository;
    
    @Autowired
    private CardViewRepository cardViewRepository;

    @Override
    public Response process(NumberEntry numberEntry) {
        Response response = Response.Builder().status(Response.STATUS_PARAM_ERROR);

        if(netUnitRepository.findOne(numberEntry.getNetunit()) == null)
            return response.message("网元不存在");

        if(numberEntryRepository.existsByNetunitAndSlotAndTsAndIdNot(
        		numberEntry.getNetunit(), 
        		numberEntry.getSlot(), 
        		numberEntry.getTs(), 
        		numberEntry.getId()))
            return response.message("该网元的槽位和时隙已经配置");

        if(numberEntryRepository.existsByNumberAndIdNot(
        		numberEntry.getNumber(), 
        		numberEntry.getId()))
            return response.message("用户号码重复");

        //CardView card = cardViewDao.getCardBySlot(numberEntry.getNetunit(), numberEntry.getSlot());
        CardView card = cardViewRepository.findOneByNetUnitIdAndSlot(numberEntry.getNetunit(), numberEntry.getSlot());

        if(card == null || !PduConstants.userDataTsMap.containsKey(card.getCode()))
            return response.message("槽位不合法");

        if(PduConstants.userDataTsMap.get(card.getCode()) <= numberEntry.getTs())
            return response.message("时隙不合法");

        return response.status(Response.STATUS_SUCCESS);
    }

    @Override
    public Response checkBeforeRemove(int id) {
        return null;
    }
}
